package com.ai.controller;

import com.ai.constant.SystemConst;
import com.ai.pojo.BfmUser;
import com.ai.request.TyrzAccountReq;
import com.ai.response.TyrzAccountDTO;
import com.ai.service.ISSOLoginKeyValidService;
import com.ai.service.ITyrzService;
import com.ai.utils.Base64Util;
import com.ai.utils.CommonUtil;
import com.ai.utils.DesCryptUtil;
import com.ai.utils.DesECBUtil;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.Map;

/**
 * @author fengs
 * @description 统一认证
 * @date 2022/7/6 9:28
 */
@RestController
@RequestMapping("/cqdxai")
public class CqdxaiController {

    @Autowired
    private ITyrzService tyrzService;

    @Autowired
    private ISSOLoginKeyValidService validSsoLoginKey;

    /**
     * AI平台用户在统一认证新建时，通过调用此接口同步数据到MYSQL库AI平台的用户表中（包含增、删、改操作）
     */
    @PostMapping("/accountSync")
    public TyrzAccountDTO accountSync(@RequestBody TyrzAccountReq req, HttpServletRequest request) {
        req.setIp(CommonUtil.getIp(request));
        return tyrzService.accountSync(req);
    }

    /**
     * 人主-单点登录AI平台
     * 回调人主校验接口，通过则登录成功
     * 将人主编码加密为“AI平台”单点登录token进行登录
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/cqdxaiSsoLogin", method = {RequestMethod.GET, RequestMethod.POST})
    public void cqdxaiSsoLogin(HttpServletRequest request, HttpServletResponse response) {
        //TYRZ单点登录
        String token = request.getParameter("token");
        String mainAcctCode = request.getParameter("account");
        String index = request.getParameter("index");
        System.out.println("token:" + token + ",mainAcctCode:" + mainAcctCode + ",index:" + index);

        // 回调人主接口，校验登录有效性
        boolean loginResult = validSsoLoginKey.validSsoLoginKey("CQDXAI", token, mainAcctCode, index);

        if (!loginResult) {
            System.out.println("单点登录失败,返回首页");
            try {
                response.getOutputStream().write(new String("单点登录失败，请联系管理员").getBytes());
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }

        String cqdxaiToken = "";
        try {
            String mainAccountCode = DesECBUtil.decrypt(Base64Util.decode(mainAcctCode), SystemConst.TOKEN_VALIDATE_KEY);
            //查询账号是否需要特殊转换
            Map<String, Object> codeMap = tyrzService.queryTransByAccountCode(mainAccountCode);
            if (MapUtils.isNotEmpty(codeMap)) {
                String status = MapUtils.getString(codeMap, "status");
                if ("1000".equals(status)) {
                    mainAccountCode = MapUtils.getString(codeMap, "trans_code");
                } else if ("2000".equals(status)){
                    response.getOutputStream().write(new String("单点登录失败，该人员已注销").getBytes());
                    return;
                }

            }

            //测试用
//            String mainAccountCode = mainAcctCode;
            //账号问题特殊处理（前期建账号时未一一对应的问题）
            if ("huangbo6".equals(mainAccountCode)) {
                mainAccountCode = "huangbo";
            }
            if ("mokundong".equals(mainAccountCode)) {
                mainAccountCode = "Mokundong";
            }
//            if ("cengziran".equals(mainAccountCode)) {
//                mainAccountCode = "admin";
//            }
            BfmUser bfmUser = tyrzService.queryUserByMainCode(mainAccountCode);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("userCode", bfmUser.getUserCode());
            jsonObject.put("timestamp", new Date().getTime());

            DesCryptUtil des = new DesCryptUtil(DesCryptUtil.simpleKey); // 自定义密钥
            cqdxaiToken = des.encrypt(jsonObject.toJSONString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        String redirect = "/home/";
        try {
//            String redirectUrl = "http://136.6.202.47:8888/single?redirect=" + URLEncoder.encode(redirect, "UTF-8") + "&sso=0&type=4&token=" + cqdxaiToken;
            String redirectUrl = "http://136.30.150.23:9999/single?redirect=" + URLEncoder.encode(redirect, "UTF-8") + "&sso=0&type=4&token=" + cqdxaiToken;
            response.sendRedirect(redirectUrl);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
